package imoney.server;

import imoney.server.util.CookieBuilderServer;
import imoney.server.util.DataStoreManager;
import imoney.shared.Statics;
import imoney.shared.exception.AlreadyExistingException;
import imoney.shared.exception.NoSuchPersonException;
import imoney.shared.model.Person;

import java.io.IOException;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Servlet used to create a new user in the database. Quite simple for
 * now, but other fields might come in later.
 * @author Arnaud Peloquin
 *
 */
public class CompteServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	Logger log = Logger.getLogger(CompteServlet.class.getName());

	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException{
		resp.getWriter().write("This page should have been accessed via doPost.");
		resp.sendRedirect(Statics.DEFAULT_ERROR_URL);
	}

	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException{
		// getting html form data
		String pseudo = req.getParameter("pseudo");
		String googleID = req.getParameter("googleID");
		assert pseudo != null && googleID != null;
		
		// creating a new person in the database
		Person pers = new Person(googleID, pseudo);
		try {
			DataStoreManager.registerAndMakePersistent(pers);
			int indexOfUser = UserServlet.genericLoginPerson(googleID, getServletContext());
			Cookie cookie = CookieBuilderServer.buildIndexCookie(googleID, indexOfUser, pseudo);
			resp.addCookie(cookie);
		}
		catch(NoSuchPersonException nosuch) {
			log.info("Person creation failed: " + googleID + " (" + pseudo + ")");
		}
		catch (AlreadyExistingException aee) {
			boolean updated = DataStoreManager.updatePseudo(googleID, pseudo);
			if (updated) {
				log.info("Pseudo updated: " + pseudo);
			} else {
				log.info("Pseudo update failed: " + pseudo);				
			}
		}
		String source = req.getParameter(Statics.SRC_URL_PARAM);
		String url = (source == null) ? Statics.HOME_URL : source;
		log.info("redirecting to "+ url);
		resp.sendRedirect(url);
	}
}
